#include "utility.h"
#include "SDL_image.h"
#include "game_engine.h"
#include <iostream>
#include <iomanip>

std::string format_path( std::string path )
{
#ifndef __APPLE__
	size_t index = std::string::npos;
	index = path.find("Resources\\");
	if (index == std::string::npos)
		path = "Resources\\" + path;
#endif
    
    return path;
}

SDL_Surface* load_image( std::string filename, bool alphaFormat ) 
{
    //Temporary storage for the image that's loaded
    SDL_Surface* loadedImage = NULL;
    
    //The optimized image that will be used
    SDL_Surface* optimizedImage = NULL;

	//Make platform correct path
	filename = format_path(filename);

    //Load the image
    loadedImage = IMG_Load( filename.c_str() );

    //If nothing went wrong in loading the image
    if( loadedImage != NULL )
    {
        //Create an optimized image
		if (alphaFormat)
			optimizedImage = SDL_DisplayFormatAlpha( loadedImage );
		else
			optimizedImage = SDL_DisplayFormat( loadedImage );
        
        //Free the old image
        SDL_FreeSurface( loadedImage );
    }

    //Return the optimized image
    return optimizedImage;
}


void apply_surface( Uint32 x, Uint32 y, SDL_Surface* source, SDL_Surface* destination )
{
    //Make a temporary rectangle to hold the offsets
    SDL_Rect offset;
    
    //Give the offsets to the rectangle
    offset.x = x;
    offset.y = y;

	SDL_BlitSurface( source, NULL, destination, &offset );
}

void apply_partial_surface( Sint16 srcX, Sint16 srcY, Uint16 srcW, Uint16 srcH, Sint16 dstX, Sint16 dstY, SDL_Surface* source, SDL_Surface* destination )
{
    //Make a temporary rectangle to hold the offsets
    SDL_Rect src, dest;
    
	//source rectangle
	src.x = srcX;
	src.y = srcY;
	src.w = srcW;
	src.h = srcH;

    //Give the offsets to the rectangle
    dest.x = dstX;
    dest.y = dstY;

	SDL_BlitSurface( source, &src, destination, &dest );
}

double rand_double_range(double a, double b)
{
	return ((b-a)*((double)rand()/RAND_MAX))+a;
}

Uint32 lastFrameNumber = 0;

void log_error( std::string error )
{
	std::cerr << std::setw(8) << std::setiosflags(std::ios::fixed) << std::setprecision(3) << (SDL_GetTicks() / 1000.0) << "|" << error << std::endl;
}

void log_info( std::string info )
{
	std::cout << std::setw(8) << std::setiosflags(std::ios::fixed) << std::setprecision(3) << (SDL_GetTicks() / 1000.0) << "|" << info << std::endl;
}

PlayerSide get_opposite_side(PlayerSide side)
{
	if (side == PLAYER_LEFT)
		return PLAYER_RIGHT;
	else
		return PLAYER_LEFT;
}

Uint16 get_d10_roll()
{
	return rand() % 10 + 1;
}